// pages/give-order/give-order.js
var util = require("../../utils/util.js");
// pages/order/order.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
        giveType: '',
        addressList: [],
        number: '',
        command: '',
        isShowFreight: !1,
        showTipAddress: !0,
        maxStock: 99,
        isSubmit: false, //防止表单重新提交
        coupon: {
            price: 0.00,
            totalLength: 0,
            canUseCoupons: [],
            noCanUseCoupons: []
        },
        vouchers: {
            price: 0.00,
            totalLength: 0,
            canUseVouchers: [],
            noCanUseVouchers: []
        },
        totalDiscount: 0.00,
        actualTotal: 0,
        total: 0,
        totalCount: 0,
        transfee: 0,
        reduceAmount: 0,
        remark: "",
        couponIds: [],
        blessing: '',
        speckPath: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.type) {
            this.setData({
                giveType: options.type
            })
        } else {
            let littleThought = JSON.parse(wx.getStorageSync("littleThought"));
            if (littleThought) {
                this.setData({
                    giveType: littleThought.type,
                    blessing: littleThought.blessing,
                    speckPath: littleThought.speckPath,
                })
            }
        }
        if (options.blessing) {
            this.setData({
                blessing: options.blessing
            })
        }
        if (options.speckPath) {
            this.setData({
                speckPath: options.speckPath
            })
        }

        let orderItem = JSON.parse(wx.getStorageSync("giveOrderItem"));
        this.setData({
            orderItem: orderItem,
            number: orderItem.productNum
        })
        let pages = getCurrentPages();
        let currPage = pages.pop();
        if (currPage.data.selAddress == "yes") {
            this.setData({ //将携带的参数赋值
                addressInfo: currPage.data.item
            });
        }

        //获取订单数据
        this.loadOrderData();
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {},

    toAddress: function(e) {
        let info = e.currentTarget.dataset.info;
        let index = e.currentTarget.dataset.index;
        if (!info) {
            wx.navigateTo({
                url: "/pages/select-address/select-address?addressIndex=" + 0
            })
        } else {
            wx.navigateTo({
                url: "/pages/select-address/select-address?id=" + info.id + "&addressIndex=" + index
            })
        }

    },
    loadOrderData: function() {
        var addrId = 0;
        if (this.data.addressInfo != null) {
            addrId = this.data.addressInfo.addrId;
        }
        wx.showLoading({
            mask: true
        });

        //获取优惠
        this.getDiscount(this.data.orderItem.productId);

        //获取商品信息
        this.getGoodsDetail(this.data.orderItem.productId);


    },
    getGoodsDetail: function(e) {
        const _this = this;
        util.request(getApp().api.goods.detail, { productId: e }).then(
            function(res) {
                if (res.code == 200) {
                    let goods = res.data[0];
                    goods.sellPrice = goods.sellPrice / 100;
                    goods.trackFee = goods.trackFee / 100;
                    _this.setData({
                        goods: goods
                    });
                    if (_this.data.maxStock < _this.data.number) {
                        _this.setData({
                            number: _this.data.maxStock //弹窗里面的+-数值
                        })
                    }
                    _this.calc()
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
    },
    inputBlur: function(e) {
        var t = '{"' + e.currentTarget.dataset.name + '":"' + e.detail.value + '"}';
        this.setData(JSON.parse(t));
    },
    showFreightRule: function() {
        this.setData({
            isShowFreight: !0
        })
    },
    closeFreight: function() {
        this.setData({
            isShowFreight: !1
        })
    },

    changeData: function() {

    },
    toPay: function() {
        let _this = this;

        if (_this.data.giveType == 1 && !this.data.addressList[0]) {
            wx.showToast({
                title: '请选择地址',
                icon: "none"
            });
            return false;
        }


        if (_this.data.isSubmit) {
            return false
        } else {
            _this.setData({
                isSubmit: true
            });
            const openid = wx.getStorageSync('openid');
            var data = {
                openId: openid,
                orderType: 1,
                baseId: _this.data.orderItem.productId,
                giveType: _this.data.giveType,
                productNum: _this.data.number,
                giveNews: _this.data.blessing, //文字祝福
                giveSpeak: _this.data.speckPath, //语音祝福
                discountCoupon: _this.data.coupon.id ? _this.data.coupon.id : '',
                cashCoupon: _this.data.vouchers.id ? _this.data.vouchers.id : '',
                orderAmount: _this.data.totalMoney * 100,
                productHeft: _this.data.goods.productHeft * _this.data.number,
                freight: _this.data.totalFreight * 100,
                command: _this.data.command,
                address: _this.data.addressList,
                deliveryNum: 1, //配送次数
            };

            util.post(
                getApp().api.wxpay.give,
                data
            ).then(
                function(res) {
                    _this.setData({
                        isSubmit: false
                    });
                    if (res.code == 200) {
                        wx.requestPayment({
                            timeStamp: res.timeStamp,
                            nonceStr: res.nonceStr,
                            package: res.package,
                            signType: res.signType,
                            paySign: res.paySign,
                            success: function(t) {},
                            fail: function(t) {},
                            complete: function(t) {
                                wx.removeStorageSync('littleThought');
                                if ("requestPayment:fail" != t.errMsg && "requestPayment:fail cancel" != t.errMsg) {
                                    wx.redirectTo({
                                        url: "/pages/pay-suc/pay-suc?orderId=" + res.orderId + '&type=' + 2
                                    })
                                } else {
                                    wx.showModal({
                                        title: "提示",
                                        content: "订单尚未支付",
                                        showCancel: !1,
                                        confirmText: "确认",
                                        success: function(t) {
                                            t.confirm && wx.redirectTo({
                                                // url: "/pages/order-list/order-list?id=1"
                                                url: "/pages/pay-suc/pay-suc?orderId=" + res.orderId + '&type=' + 2 + '&giveType=' + _this.data.giveType
                                            });
                                        }
                                    });
                                }
                            }
                        })
                    } else {
                        wx.showToast({
                            title: res.msg, //提示的内容,
                            icon: "none", //图标,
                            //duration: 1500, //延迟时间,
                            mask: false, //显示透明蒙层，防止触摸穿透,
                        });
                        setTimeout(function() {
                            wx.hideToast();
                        }, 1500);
                        return
                    }
                },
                function() {
                    _this.setData({
                        isSubmit: false
                    });
                }
            )
        }
    },
    numberSub: function() {
        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1,
        });
        this.calc();
        this.getDiscount(this.data.orderItem.productId);
    },
    numberAdd: function() {
        this.setData({
            number: this.data.number + 1 <= this.data.maxStock ? this.data.number + 1 : this.data.maxStock,
        });
        this.calc();
        this.getDiscount(this.data.orderItem.productId);
    },
    numberBlur: function(e) {
        var num = ~~e.detail.value;
        if (num <= 0) num = 1;
        if (this.data.maxStock && (num > this.data.maxStock)) num = this.data.maxStock;
        this.setData({ number: num });
        this.calc();
        this.getDiscount(this.data.orderItem.productId);
    },
    calc: function(e) {
        let totalDiscount = 0;
        let totalFreight = 0;

        totalDiscount = (~~this.data.vouchers.price + ~~this.data.coupon.price) / 100;
        totalFreight = this.onceFreightCalculationFormula(this.data.number, this.data.goods.productHeft / 1000);

        this.setData({
            totalDiscount: totalDiscount,
            totalFreight: totalFreight,
            totalMoney: this.data.goods.sellPrice * this.data.number - totalDiscount + totalFreight
        });
        console.log(this.data.totalMoney);
    },
    /**
     * 单次价格配送计算公式 (虽然可以合并，以防需求变化 还是分开来写)
     */
    onceFreightCalculationFormula: function(num, weight) {
        // if (weight * num <= 20) {
        return 0
            // } else {
            //     return (Math.ceil(+weight * num) - 20) * 1
            // }
    },

    //获取优惠
    getDiscount: function(e) {
        const _this = this;
        util.request(getApp().api.coupon.default, { baseId: e, num: _this.data.number }).then(
            function(res) {
                if (res.code == 200) {
                    if (res.data != null) {
                        if (res.data.type == '0') {
                            _this.setData({
                                coupon: res.data
                            })
                        } else {
                            _this.setData({
                                vouchers: res.data
                            })
                        }
                    }

                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                }
            }
        );
    },
    toCoupon: function() {
        wx.navigateTo({
            url: "/pages/coupon/coupon?baseId=" + this.data.orderItem.productId + '&num=' + this.data.number
        })
    },
    toVoucher: function() {
        wx.navigateTo({
            url: "/pages/voucher/voucher?baseId=" + this.data.orderItem.productId + '&num=' + this.data.number
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

});